package net.office.controller;

import net.office.bean.StaffInfo;
import net.office.service.LoginService;
import net.office.utils.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LogController {

    @Autowired
    private LoginService loginService;

    /*获取验证码*/
    @RequestMapping("/getAuthCode.do")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response){
        String authCode = AuthCode.getAuthCode();
        request.getSession().setAttribute("authCode", authCode);//保存到session上
        try{
            ImageIO.write(AuthCode.getAuthImg(authCode), "JPEG", response.getOutputStream());
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /*登录*/
    @RequestMapping("/login.do")
    public String login(@RequestParam("staffNo") String staffNo,
                        @RequestParam("staffName") String staffName,
                        @RequestParam("staffPassword") String staffPassword,
                        @RequestParam("authCode") String authCode,
                        HttpSession session, Model model){

        if(!(session.getAttribute("authCode")).equals(authCode)){
            model.addAttribute("msg", "authCode");
            return "login";
        }

        StaffInfo staffInfo = new StaffInfo();
        staffInfo.setStaffNo(staffNo);
        staffInfo.setStaffName(staffName);
        staffInfo.setStaffPassword(staffPassword);

        StaffInfo res = loginService.login(staffInfo);
        if(res != null){
            session.setAttribute("staff", res);
            model.addAttribute("msg", "right");
            return "user";
        }

        model.addAttribute("msg", "staff");
        return "login";
    }

    /*登出*/
    @RequestMapping("/logout.do")
    public String logout(HttpSession session){
        session.removeAttribute("staff");
        return "login";
    }
}
